package com.lg.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lg.erp.entity.*;
import com.lg.erp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SUser user = userMapper.selectOne(new QueryWrapper<SUser>().lambda().eq(SUser::getUsername, s));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SMenu> functions = userMapper.selectMenusByUsername(s);
        List<SRole> roles = userMapper.selectRolesByUsername(s);
        StringBuilder stringBuilder = new StringBuilder();
        functions.forEach(functions1 -> stringBuilder.append(functions1.getMenuName()+","));
        roles.forEach(role -> stringBuilder.append("ROLE_"+role.getRoleName()+","));
        if(stringBuilder.length() > 0){
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString()));
    }
}